<template>
  <div class="search">
    <van-nav-bar title="搜索中心" left-arrow @click-left="$router.back()"></van-nav-bar>
    <van-search
      v-model.trim="keyword"
      show-action
      placeholder="请输入搜索关键词"
      shape="round"
      @input="inputFn"
      @search="search(keyword)"
    >
      <template #action>
        <div @click="search(keyword)">搜索</div>
      </template>
    </van-search>

    <!-- 推荐 -->
    <van-cell-group v-if="sugList.length > 0">
      <van-cell
        v-for="(item, index) in sugList"
        :key="index"
        icon="search"
        @click="search(keyword)"
      >
        <template #title>
          <div v-html="highLight(item)"></div>
        </template>
      </van-cell>
    </van-cell-group>

    <!-- 历史记录 -->
    <van-cell-group v-else >
      <van-cell title="历史记录"></van-cell>
      <van-cell @click="search(item)" :title="item" v-for="item in searchList" :key="item">
        <van-icon name="close" @click="del(item)" />
      </van-cell>
    </van-cell-group>
  </div>
</template>

<script>
import { getSuggestion } from '@/api/search'
import { setHistory, getHistory } from '@/utils/storage'
export default {
  name: 'Search',
  data () {
    return {
      keyword: '',
      sugList: [],
      searchList: getHistory()
    }
  },
  methods: {
    inputFn () {
      clearTimeout(this.timer)
      this.timer = setTimeout(async () => {
        if (!this.keyword) {
          this.sugList = []
          return
        }
        const res = await getSuggestion(this.keyword)
        this.sugList = res.data.options
      }, 500)
    },
    highLight (str) {
      const reg = new RegExp(this.keyword, 'gi')
      return str.replace(reg, match => {
        return `<span style='color: red;'>${match}</span>`
      })
    },
    search (keyword) {
      if (!keyword) return this.$toast('请输入搜索关键词')
      console.log(this.searchList)
      this.searchList = this.searchList.filter(item => item !== keyword)
      this.searchList.unshift(keyword)
      setHistory(this.searchList)
      // console.log('跳转', keyword)
      this.$router.push({
        path: '/search/result',
        query: {
          keyword
        }
      })
    },
    del (keyword) {
      this.searchList = this.searchList.filter(item => item !== keyword)
      setHistory(this.searchList)
    }
  }

}
</script>

<style></style>
